<template>
    <div class="fileUpload">
        <el-upload
            ref="uploadFileRef"
            :show-file-list="false"
            :action="uploadUrl"
            :limit="limit"
            :on-exceed="handleExceed"
            :accept="props.acceptTypes"
            :headers="headers"
            :data="otherParams"
            :before-upload="beforeUploadHandler"
            :on-change="handleChange"
            :on-success="successHandler"
            :on-error="errorHandler">
            <el-button class="submit" type="default">选择文件</el-button>
            <slot name="tip"> </slot>
        </el-upload>
        <div v-if="showVisible">
            <div class="fileList" v-for="item in Data.fileList" :key="item.id">
                <img class="icon" src="@/assets/imgs/sys/file.png" alt="" />
                <span>{{ item.name }}</span>
                <img class="del" @click="delHandler" src="@/assets/imgs/sys/file-del.png" alt="" />
            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, reactive, computed, watch } from 'vue';
import storage from '@/commons/storage.js';
import constants from '@/commons/constants';
const emit = defineEmits(['fileStateChange', 'clear']);
const uploadFileRef = ref(null);
const showVisible = ref(false);
const Data = reactive({ fileList: [] });
let tempUrl = constants.PEM_UPLOAD_URL;
let uploadUrl = ref(tempUrl);
const headers = reactive({
    'ZW-PLATFORM-TOKEN': storage.get('ZW-TOKEN'),
    'ZW-TENANT-ID': storage.get('ZW-TENANT-ID')
});
const props = defineProps({
    // 文件类型
    acceptTypes: { type: String, default: '.pem' },
    // 文件大小
    maxSize: { type: Number, default: 1 },
    // 其他校验条件
    validator: { type: Function, default: () => {} },
    // 文件数量
    limit: { type: Number, default: 1 },
    // 商户号
    merId: { type: String, default: '' },
    // 文件回显
    files: {
        type: Array,
        default: () => {
            return [];
        }
    }
});

watch(
    () => props.files,
    val => {
        if (val?.length) {
            Data.fileList = [];
            props.files.map(x => {
                Data.fileList.push({
                    name: x.name,
                    url: x.url,
                    id: new Date().getTime()
                });
            });
            showVisible.value = true;
        }
    },
    { immediate: true, deep: true }
);

const otherParams = computed(() => {
    return { merId: props.merId };
});
const beforeUploadHandler = file => {
    // 考虑到服务端有文件类型和文件大小限制，所以这俩为必须校验
    if (!file.name.endsWith('.pem')) {
        emitHandler({ msg: `只支持 pem 格式的文件!` });
        return false;
    }
    if (file.size / 1024 / 1024 > props.maxSize) {
        emitHandler({ msg: `文件大小限制${props.maxSize}M以内！` });
        return false;
    }
    if (props.merId === '') {
        emitHandler({ msg: `请输入商户号！` });
        return false;
    }
    return props.validator(file);
};
// 文件监听
const handleChange = (uploadFile, uploadFiles) => {
    Data.fileList.length = 0;
    uploadFiles.map(item => {
        Data.fileList.push({
            name: item.name,
            url: item.name,
            id: new Date().getTime()
        });
        emitHandler({ fileName: item.name });
    });
    showVisible.value = true;
};
const successHandler = res => {
    if (res.code === 0) {
        emitHandler({ fileUrl: res.data.uri });
    } else {
        emitHandler({ msg: res.msg || '文件上传失败，请刷新重试！' });
    }
};
const errorHandler = res => {
    emitHandler({ msg: res.msg || '文件上传失败，请刷新重试' });
};
const handleExceed = files => {
    uploadFileRef.value.clearFiles();
    uploadFileRef.value.handleStart(files[0]);
};
const emitHandler = ({ fileUrl, fileName, msg }) => {
    emit('fileStateChange', { fileUrl, fileName, msg });
};
// 删除
const delHandler = () => {
    uploadFileRef.value.clearFiles();
    Data.fileList.length = 0;
    showVisible.value = false;
    emit('clear');
};
</script>
<style lang="scss" scoped>
.fileUpload :deep(.el-upload-list) {
    display: none;
}
.fileList {
    display: flex;
    padding: 6px 12px;
    background: #f3f3f3;
    align-items: center;
    width: 412px;
    height: 32px;
    box-sizing: border-box;
    margin-top: 16px;
    .icon {
        width: 20px;
        height: 20px;
        margin-right: 7px;
    }
    span {
        font-size: 14px;
        font-weight: 300;
        color: #33302d;
        line-height: 14px;
        flex: 1;
    }
    .del {
        width: 14px;
        height: 14px;
        cursor: pointer;
    }
}
</style>
